<template>
  <div class="list-containner">
    <el-form class="search-panel" v-model="searchForm" :inline="true">
      <el-form-item
        label-width="90px"
        class="search-input"
        label="人员名称："
        prop="name"
      >
        <el-input v-model="searchForm.name" placeholder="人员名称"></el-input>
      </el-form-item>
      <el-form-item
        label-width="90px"
        class="search-person"
        label="人员状态:"
        prop="person"
      >
        <el-select v-model="formData.personStatus" placeholder="请选择人员状态">
          <el-option
            v-for="item in personStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label-width="90px"
        class="search-account"
        label="是否开户:"
        prop="account"
      >
        <el-select v-model="formData.openAccount" placeholder="全部">
          <el-option
            v-for="item in accountStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="table-panel">
      <el-row class="table-operate">
        <el-button type="primary" icon="el-icon-plus" @click="toAddPorsonnel">
          新增人员
        </el-button>
        <el-button @click.native.prevent="personExport" type="primary" icon="el-icon-download">人员导出</el-button>
        <!-- <el-button @click="importItems">
          导入 <i class="el-icon-upload2" />
        </el-button> -->
        <!-- <el-button @click="exitItems"> 批量退场 </el-button> -->
        <!-- <el-button @click="deleteItems">
          批量删除</el-button
        > -->
        <!-- <el-button @click="toOpenCard"> 去开户 </el-button> -->
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6" class="table-left" style="border-right:1px solid #e8e8e8">
          <el-tree
            accordion
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            ref="tree"
          ></el-tree>
        </el-col>
        <el-col :span="18" class="table-right">
          <el-table
            ref="multipleTable"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
          <el-table-column type="selection"  width="42" align="center"> </el-table-column>
            <el-table-column
              type="index"
              width="55"
              label="序号"
              align="center"
            >
            </el-table-column>
            <!-- <el-table-column prop="name" label="姓名" width="80" align="center">
            </el-table-column> -->
            <el-table-column
              prop="name"
              label="姓名"
              min-width="80"
              align="center"
            >
              <template slot-scope="scope">
                {{ scope.row.name
                }}<span v-show="scope.row.isTeamLeader === 1">(班组长)</span>
              </template>
            </el-table-column>

            <!-- <el-table-column
              prop="idPhoto"
              label="证件照"
              min-width="100"
              align="center"
            >
              <template slot-scope="scope">
                <el-image
                  style="width: 80px; height: 40px"
                  :src="scope.row.idPhoto"
                  fit="contain"
                  :lazy="true"
                ></el-image>
              </template>
            </el-table-column> -->
            <el-table-column
              prop="statusName"
              label="人员状态"
              min-width="80"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="isOpenCard"
              label="是否开户"
              align="center"
              min-width="80"
            >
              <template slot-scope="scope">
                {{ scope.row.openAccount==1 ? "已开户" : "未开户" }}
              </template>
            </el-table-column>
            <el-table-column prop="workTypeName" label="工种" align="center">
            </el-table-column>
            <el-table-column prop="dailyWage" label="日工资" align="center">
              <template slot-scope="scope">
                <span>¥{{ scope.row.dailyWage }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="alimony" label="生活费" align="center">
              <template slot-scope="scope">
                <span>¥{{ scope.row.alimony }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" min-width="200" fixed="right">
              <template slot-scope="scope">
                <el-button
                  :disabled="!(scope.row.status == 1)"
                  @click.native.prevent="exitRow(scope.row, tableData)"
                  type="text"
                  icon="el-icon-remove-outline"
                  >退场</el-button
                >
                <el-button
                  @click.native.prevent="updateRow(scope.row)"
                  type="text"
                  icon="el-icon-edit"
                  >修改</el-button
                >
                <el-button
                  @click.native.prevent="deleteRow(scope.row.id)"
                  type="text"
                  icon="el-icon-delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="page">
        <div class="page-tag">
          共{{ Math.ceil(totalData / searchForm.pageSize) }}页/{{
            totalData
          }}条数据
        </div>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="searchForm.currentPage"
          :page-size="searchForm.pageSize"
          layout="sizes,prev, pager, next, jumper"
          :total="totalData"
        >
        </el-pagination>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  getTree,
  getPersonByTeamId,
  getPersonByserviceCorporationId,
  deletePersonnel,
  personExit,
  exportPersonInf
} from "@/api/worker";
export default {
  data() {
    return {
      formData: {
        personStatus:-1,
        openAccount:-1,
      },
      searchForm: {
        currentPage: 1,
        pageSize: 10,
        team_id: null,
        service_corporation_id: null,
        name:null,
        open_account:0,
        status:0,
        // open_account:this.formData.personStatus,
        // status:this.formData.openAccount,
      },
      personStatusList: [
        {
          value: -1,
          label: "全部",
        },
        {
          value: 0,
          label: "未进场",
        },
        {
          value: 1,
          label: "进场",
        },
        {
          value: 2,
          label: "进场中",
        },
        {
          value: 4,
          label: "退场待确认",
        },
        {
          value: 3,
          label: "退场",
        },
        
      ],
      accountStatusList: [
        {
          value: -1,
          label: "全部",
        },
        {
          value: 0,
          label: "未开户",
        },
        {
          value: 1,
          label: "已开户",
        },
      ],
      flag: 1,
      listNum: "",
      //   totalPage:50,
      totalData: 1000,
      src: "./static/addImg.png",
      options: [1, 10, 20, 30, 40],
      treeData: [
        {
          label: "劳务公司1",
          children: [
            {
              label: "x班组",
              children: [
                {
                  label: "x班组1",
                },
                {
                  label: "x班组2",
                },
                {
                  label: "x班组3",
                },
              ],
            },
          ],
        },
        {
          label: "劳务公司2",
          children: [
            {
              label: "x班组",
              children: [
                {
                  label: "x班组1",
                },
              ],
            },
            {
              label: "xx班组",
              children: [
                {
                  label: "xx班组1",
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "name",
      },
      tableData: [],
    };
  },
  created() {
    this.getTreeData();
    this.getTableData();
  },
  methods: {
    // getImgUrl(res) {
    //   let urlCreator = window.URL || window.webkitURL;
    //   let imageUrl = urlCreator.createObjectURL(res);
    //   console.log(imageUrl)
    //   return imageUrl
    // },

    personExport(){
      var dd = new Date()
      var y= dd.getFullYear()
      var m= dd.getMonth()+1
      if(m<10) m = '0'+m
      var d = dd.getDate()
      if(d<10) d = '0'+d
      var date=y+'-'+m+'-'+d
      exportPersonInf().then(res=>{
        let blob = new Blob([res]);//response.data为后端传的流文件
        console.log(blob);
        let downloadFilename = date+"人员.xlsx";//设置导出的文件名  用moment时间插件对文件命名防止每次都是一样的文件名
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        //兼容ie浏览器
          window.navigator.msSaveOrOpenBlob(blob)
        }else {
        //谷歌,火狐等浏览器
          let url = window.URL.createObjectURL(blob);
          let downloadElement = document.createElement("a");
          downloadElement.style.display = "none";
          downloadElement.href = url;
          downloadElement.download = downloadFilename;
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement);
          window.URL.revokeObjectURL(url);
        }
      }).catch(function (err) {
        this.$message.error(err)
        console.log(err)
      }).finally(function () {
          // this.tableLoading = false;
      })
    },
    // 修改选择状态
    handleSelectionChange(res) {
      //   console.log(res)
      this.tableData.forEach((e) => {
        e.isSelected = false;
      });
      if (res.length > 0)
        res.forEach((e) => {
          this.tableData[e.number - 1].isSelected = true;
        });
      //   console.log(this.tableData);
    },
    //处理响应的表格数据
    processTableData() {
      for (let data of this.tableData) {
        if (data.status === 1) {
          data.statusName = "进场";
        } else if (data.status === 3) {
          data.statusName = "退场";
        } else if (data.status === 4) {
          data.statusName = "退场待确认";
        }
      }
    },
    //发送请求获取表格数据
    getTableData() {
      if (this.flag === 0) {
        // 根据班组id查询班组人员————选择班组
        getPersonByTeamId({
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        team_id: this.searchForm.team_id,
        service_corporation_id: this.searchForm.service_corporation_id,
        name:this.searchForm.name,
        status:this.formData.personStatus==-1?null:this.formData.personStatus,
        open_account:this.formData.openAccount==-1?null:this.formData.openAccount,
      }).then((res) => {
          // console.log(res);
          this.tableData = res.data.data.records;
          this.totalData = res.data.data.total;
          this.processTableData();
        });
      } else {
        // 根据劳务公司id查询劳务公司人员————选择劳务公司
        getPersonByserviceCorporationId({
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        team_id: this.searchForm.team_id,
        service_corporation_id: this.searchForm.service_corporation_id,
        name:this.searchForm.name,
        status:this.formData.personStatus==-1?null:this.formData.personStatus,
        open_account:this.formData.openAccount==-1?null:this.formData.openAccount,
      }).then((res) => {
          // console.log(res);
          this.tableData = res.data.data.records;
          this.totalData = res.data.data.total;
          this.processTableData();
        });
      }
    },
    // 树状图选择数据
    handleNodeClick(data) {
      let node = this.$refs.tree.getCurrentNode();
      // console.log(node);
      if (node.children == null) {
        this.flag = 0;
        // console.log("班组");
        this.searchForm.team_id = data.id;
        this.searchForm.service_corporation_id = null;
        this.getTableData();
      } else {
        this.flag = 1;
        // console.log("劳务公司");
        this.searchForm.service_corporation_id = data.id;
        this.searchForm.team_id = null;
        this.getTableData();
      }
    },
    //更改每页数据
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.searchForm.pageSize = val;
      // console.log(this.searchForm);
      this.getTableData();
    },
    //更改当前页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.searchForm.currentPage = val;
      this.getTableData();
    },
    //导入
    importItems() {
      console.log("导入");
    },
    //判断是否有选中
    EmptySelect() {
      let empty = false;
      this.tableData.forEach((e) => {
        if (e.isSelected == true) empty = true;
      });
      return empty;
    },
    //一键退场
    exitItems() {
      //   console.log("一键退场");
      let isExit = false;
      this.tableData.forEach((e) => {
        if (e.isSelected == true && e.status == "未退场") isExit = true;
      });
      if (this.EmptySelect()) {
        if (isExit) {
          this.$confirm(
            "是否确认退场所选人员，一键退场人员默认下次结算",
            "一键退场",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "none",
            }
          )
            .then(() => {
              this.$message({
                type: "none",
                message: "已退场，待确认！",
              });
              this.tableData.forEach((e) => {
                if (e.isSelected == true && e.status == "未退场")
                  e.status = "退场待确认";
              });

              //   清楚选择状态
              this.$refs.multipleTable.clearSelection();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消退场",
              });
            });
        } else {
          this.$message({
            type: "warning",
            message: "所选人员不需要退场!",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择退场人员!",
        });
      }
    },
    //一键删除
    deleteItems() {
      //   console.log("一键删除");
      // console.log(this.tableData)
      // console.log(this.EmptySelect())
      if (this.EmptySelect()) {
        this.$confirm("是否批量删除所选人员", "批量删除", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "none",
        })
          .then(() => {
            this.$message({
              type: "none",
              message: "已删除!",
            });
            this.tableData = this.tableData.filter((e) => {
              return e.isSelected == false;
            });
            //   清楚选择状态
            // this.$refs.multipleTable.clearSelection();
          })

          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消批量删除",
            });
          });
      } else {
        this.$message({
          type: "warning",
          message: "请选择删除人员!",
        });
      }
    },
    //去开户
    toOpenCard() {
      console.log("去开户");
    },
    //新增人员
    toAddPorsonnel() {
      console.log("新增人员");
      this.$router.push({ path: "/worker/add" });
    },
    //退场
    exitRow(row, data) {
      this.$confirm(
        "是否确认退场当前人员，退场后需选择是否进行结算操作",
        "退场",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "none",
        }
      )
        .then(() => {
          let ids = []
          ids.push(row.id)
          personExit(ids).then((res) => {
            this.$message({
              type: "success",
              message: "已退场!",
            });
            this.getTableData();
            this.$confirm("是否进行结算操作", "结算", {
              confirmButtonText: "结算",
              cancelButtonText: "下次结算",
              type: "none",
            })
              .then(() => {
                console.log("去结算");
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "下次结算",
                });
              });
          });

          // this.tableData[index].status = "退场待确认";
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退场",
          });
        });
    },
    //修改
    updateRow(data) {
      console.log(data);
      this.$router.push({ path: "/worker/add", query: { id: data.id } });
    },
    //删除
    deleteRow(id) {
      // console.log(id);
      this.$confirm("此操作将永久删除该用户，是否继续？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePersonnel([id]).then((res) => {
            // console.log(res)
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getTableData();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    getTreeData() {
      getTree().then((res) => {
        // console.log(res);
        this.treeData = res.data.data;
      });
    },
    onSubmit() {
      // console.log(this.searchForm);
      this.getTableData()
    },
  },
};
</script>